import React, { Component } from 'react';
import './workshop-mgt.css';
import { Menu, Dropdown, Button, message, Input, Table, Modal, Select } from 'antd';
import { DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button/linkButton.jsx';
import { reqOrganListByParentOrgid2, reqWorkshopSearchByOrgid, reqWorkshopSearchByName, reqAddWorkshopInfor, reqEditWorkshopInfor, reqDeleteWorkshop, reqDeleteUser } from '../../api';
import AddWorkshopForm from '../../components/Modal/add-workshop-form';
import EditWorkshopForm from '../../components/Modal/edit-workshop-form';
import { connect } from 'react-redux';
import { getRolesButtons } from '../../utils/storageUtils';
import editIcon from '../../assets/image/edit.png'
import deleteIcon from '../../assets/image/delete.png'
const { Search } = Input;
const { confirm } = Modal;
const { Option } = Select;

class WorkshopMgt extends Component {

  state = {
    workShopList: [],
    organList: [],
    visible: '0',
    loading: false,
    searchType: 'org_search',
    roleButtons: [], // 有权限的按钮
  };
  handleSearchType = (e) => {  // 修改查找类型
    this.setState({
      searchType: e
    })
  };

  showSearchByType = (searchType) => {  // 根据查找类型显示不同的搜索框
    if (searchType === 'name_search') {
      return (
        <Search
          className='workshop-header-search'
          placeholder="根据部门名称搜索"
          enterButton="搜索"
          size="middle"
          onSearch={(value) => this.handleNameSearch(value)}
          loading={this.state.loading}
        />
      )
    } else {
      return (
        <Select
          className='workshop-header-dropdown'
          style={{ width: 170 }}
          showSearch
          placeholder="请选择矿区"
          onChange={(e) => this.getworkShopList(e)}  // 返回选中项的value值 
        >
          {this.state.organList.map((item) => <Option value={item.org_id}>{item.org_name}</Option>)}
        </Select>
      )
    }
  };

  handleNameSearch = async (value) => {   // 按姓名查找工区 
    const ws_pid = this.props.user.org.org_id;
    const ws_name = value;
    const result = await reqWorkshopSearchByName(ws_pid, ws_name);
    if (result.code === 200) {
      const workShopList = result.data;
      workShopList.map((item1, index) => {   // 将ws_pid 对应的 组织名称找出来，并放入workshopList中用于显示
        if (this.state.organList) {
          this.state.organList.map((item2) => {
            if (item1.ws_pid === item2.org_id) {
              workShopList[index]['org_name'] = item2.org_name;
            }
          })
        }
      })
      this.setState({
        workShopList
      })
    } else {
      message.error(result.data);
    }
  };

  initColumns = () => {
    this.columns = [
      {
        title: '部门名称', dataIndex: 'ws_name', key: 'ws_name',
        sorter: {
          compare: (a, b) => a.ws_name.localeCompare(b.ws_name),
        },
      },
      { title: '所属矿区', dataIndex: 'org_name', key: 'org_name' },
      { title: '联系方式', dataIndex: 'ws_contact', key: 'ws_contact' },
      { title: '部门地址', dataIndex: 'ws_address', key: 'ws_address' },
      { title: '部门员工数量', dataIndex: 'ws_number_prople', key: 'ws_number_prople' },
      { title: '备注', dataIndex: 'ws_remark', key: 'ws_remark' },
      {
        title: '操作',
        dataIndex: '',
        key: 'action1',
        width: 120,
        render: (workshopInfo) => (
          <span>
            <LinkButton onClick={this.state.roleButtons.indexOf("workSpace-edit") === -1 ? this.noRightMessage : () => this.editShow(workshopInfo)}>
              <img src={editIcon} alt="" />
            </LinkButton>
            <LinkButton onClick={this.state.roleButtons.indexOf("workSpace-delete") === -1 ? this.noRightMessage : () => this.showDeleteConfirm(workshopInfo)}>
              <img src={deleteIcon} alt="" />
            </LinkButton>
          </span>
        ),
      },
      {
        title: '',
        dataIndex: '',
        key: 'action2',
        width: 130,
        render: (workshopInfo) => <LinkButton onClick={() => this.WorkUserMgtShow(workshopInfo)}>
          <div className='lookBtn'>
            部门用户管理
          </div>
        </LinkButton>   //this.state.roleButtons.indexOf("") === -1 ? this.noRightMessage :  
      },
    ];
  }

  getworkShopList = async (e) => {   // 获取工区列表 
    var ws_pid;
    if (e) {
      ws_pid = e;
    } else {
      ws_pid = this.props.user.org.org_id;
    }
    this.setState({ loading: true })
    const result = await reqWorkshopSearchByOrgid(ws_pid);
    this.setState({ loading: false });
    console.log("获取所有工区", result)
    if (result.code === 200) {
      const workShopList = result.data;
      workShopList.map((item1, index) => {   // 将ws_pid 对应的 组织名称找出来，并放入workshopList中用于显示
        if (this.state.organList) {
          this.state.organList.map((item2) => {
            if (item1.ws_pid === item2.org_id) {
              workShopList[index]['org_name'] = item2.org_name;
            }
          })
        }
      })
      this.setState({
        workShopList
      })
    } else {
      message.error(result.data);
    };

  }

  getOrganList = async () => {  // 获取用户权限内的全部组织
    const org_pid = this.props.user.org.org_id;
    this.setState({ loading: true })
    const result = await reqOrganListByParentOrgid2(org_pid);
    console.log("获取所有组织", result);
    this.setState({ loading: false });
    const organList = result.data;
    this.setState({
      organList
    })
  }

  getroleButtons = () => {  // 获取该模块的有权限的按钮
    getRolesButtons().map((item) => {
      if (item.key === '/workshop-mgt') {
        this.setState({
          roleButtons: item.buttons
        })
      }
    })
  }

  noRightMessage = () => {
    message.error("无访问权限！");
  }

  addShow = () => {
    this.setState({
      visible: '1'
    })
  }
  addWorkshopInfor = async () => {  // 创建工区
    this.setState({
      visible: '0'
    })
    // 1、获取输入的数据
    const ws_name = this.formRef.current.getFieldValue('ws_name');
    const ws_pid = this.formRef.current.getFieldValue('org_id');
    const ws_contact = this.formRef.current.getFieldValue('ws_contact');
    const ws_address = this.formRef.current.getFieldValue('ws_address');
    const ws_remark = this.formRef.current.getFieldValue('ws_remark') ? this.formRef.current.getFieldValue('ws_remark') : " ";
    console.log('获取的数据', ws_name, ws_pid, ws_contact, ws_address, ws_remark);
    // 2、发送请求 添加组织
    const result = await reqAddWorkshopInfor(ws_name, ws_pid, ws_contact, ws_address, ws_remark);
    if (result.code === 200) {
      message.success("添加部门成功！");
      //5.重新显示列表
      this.getworkShopList();
    }
  }

  editShow = (workshopInfo) => {
    console.log("editworkshop", workshopInfo)
    this.workshopInfo = workshopInfo;
    this.setState({
      visible: '2'
    })
  }
  editWorkshopInfor = async () => {   // 编辑工区信息
    //1.取消对话框
    this.setState({
      visible: '0'
    })
    //2.获取参数，准备数据  
    const ws_id = this.workshopInfo.ws_id;
    const ws_name = this.formRef.current.getFieldValue('ws_name');
    const ws_pid = this.formRef.current.getFieldValue('org_id');
    const ws_contact = this.formRef.current.getFieldValue('ws_contact');
    const ws_address = this.formRef.current.getFieldValue('ws_address');
    const ws_remark = this.formRef.current.getFieldValue('ws_remark');
    console.log('获取的数据', ws_id, ws_name, ws_pid, ws_contact, ws_address, ws_remark);
    //4.发送请求,修改信息
    const result = await reqEditWorkshopInfor(ws_id, ws_name, ws_pid, ws_contact, ws_address, ws_remark);
    if (result.code === 200) {
      message.success("成功修改部门信息！");
      //5.重新显示列表
      this.getworkShopList();
    }
  }

  // 对话框取消按钮
  handleCancel = () => {
    this.setState({
      visible: '0'
    })
  }

  handleDeleteOnOk = async (workshopInfo) => {  // 删除onOk
    this.setState({
      visible: '0'
    })
    const ws_id = workshopInfo.ws_id;
    const ws_pid = workshopInfo.ws_pid;
    const result = await reqDeleteWorkshop(ws_id, ws_pid);
    if (result.code === 200) {
      message.success("部门已删除！");
      this.getworkShopList();
    }
  };

  showDeleteConfirm = (workshopInfo) => {   // 删除响应函数
    confirm({
      title: '您确定要删除该部门吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => this.handleDeleteOnOk(workshopInfo)
    })
  };

  WorkUserMgtShow = (workshopInfo) => {   // 跳转 工区用户管理
    this.props.history.push({ pathname: "/workshop-mgt/showUserMgt", state: { workshop: workshopInfo } });
  }

  componentWillMount() {
    this.getroleButtons();
    this.initColumns();
    this.getOrganList();
  }
  componentDidMount() {
    this.getworkShopList();
  }

  render() {
    const { visible, loading, searchType, workShopList, roleButtons } = this.state;
    const workshopInfo = this.workshopInfo || {};
    return (
      <div className='workshop-mgt-wrapper'>
        <div className='workshop-mgt-header'>
          <div>
            <Select
              className='workshop-header-dropdown'
              style={{ width: 145 }}
              showSearch
              defaultValue="org_search"
              onChange={(e) => this.handleSearchType(e)}  // 返回选中项的value值 
            >
              <Option value='org_search' disabled={roleButtons.indexOf("workSpace-find-parentId") === -1 ? true : false}>根据矿区查找</Option>
              <Option value='name_search' disabled={roleButtons.indexOf("workSpace-find-workSpaceName") === -1 ? true : false}>根据部门查找</Option>
            </Select>
            {this.showSearchByType(searchType)}
          </div>
          {
            roleButtons.indexOf("workSpace-create") === -1 ? null : <Button type="primary" className='workshop-header-add' onClick={this.addShow}>
              创建部门
            </Button>
          }

        </div>
        <div className='workshop-mgt-content'>
          <Table
            columns={this.columns}
            dataSource={workShopList}
            size='middle'
            loading={loading}
            pagination={false}
            locale={{
              cancelSort: '点击取消排序',
              triggerAsc: '点击升序',
              triggerDesc: '点击降序'
            }}
          />

          <Modal
            title="创建部门"
            visible={visible === '1'}
            onOk={this.addWorkshopInfor}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
            destroyOnClose={true}
          >
            <AddWorkshopForm setForm={(formRef) => { this.formRef = formRef }} />
          </Modal>

          <Modal
            title="修改部门信息"
            visible={visible === '2'}
            onOk={this.editWorkshopInfor}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
            destroyOnClose={true}
          >
            <EditWorkshopForm
              wsName={workshopInfo.ws_name}
              orgId={workshopInfo.ws_pid}
              wsAddress={workshopInfo.ws_address}
              wsContact={workshopInfo.ws_contact}
              wsRemark={workshopInfo.ws_remark}
              setForm={(formRef) => { this.formRef = formRef }} />
          </Modal>
        </div>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user }),
  {}
)(WorkshopMgt); 